package com.sd.nacosdemo.controller;

import com.sd.nacosdemo.Util.ExcelUtil;
import com.sd.nacosdemo.entity.Cultivate;
import com.sd.nacosdemo.service.CultivateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ExcelController
 * @Description TODO
 * @date 2021/6/25 15:22
 * @Version 1.0
 */
@RestController
public class ExcelController {

    @Autowired
    private CultivateService cultivateService;

    @RequestMapping ("/excelImport")
    public Object excelImport(@RequestParam("file") MultipartFile file) throws IOException {

        List<Map<String, Object>> readXlsx = ExcelUtil.readXlsx(file.getInputStream(), 0, Cultivate.class);
        for (Map<String, Object> xlsx : readXlsx) {
            System.out.println(xlsx);
        }
        //将Excel数据存入到数据库中
        List<Cultivate> list = new ArrayList<>();
        for (int i=0;i<readXlsx.size();i++){
            Cultivate cultivate = new Cultivate();
            Map<String, Object> map = readXlsx.get(i);
            Long pid = Long.valueOf(map.get("pid").toString());
            Long eid = Long.valueOf(map.get("eid").toString());
            Long createId = Long.valueOf(map.get("createid").toString());
            Long departId = Long.valueOf(map.get("departid").toString());
            Date date = new Date();

            cultivate.setPid(pid);
            cultivate.setEid(eid);
            cultivate.setCreateId(createId);
            cultivate.setDepartId(departId);
            cultivate.setCreateTime(date);
            cultivate.setCultivate((String) map.get("cultivate"));
            list.add(cultivate);
        }
        for (Cultivate cultivate : list) {
            System.out.println(cultivate.toString());
        }
        int cul = cultivateService.insertList(list);
        System.out.println("=============================:"+cul);
        return "success";
    }
}
